<template>
  <div class="api-test-container">
    <h1>商品管理API测试页面</h1>
    
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <h2>商品管理API测试</h2>
        </div>
      </template>
      
      <!-- 获取商品列表 -->
      <div class="api-section">
        <h3>2.1 获取商品列表</h3>
        <el-form :model="getProductsForm" label-width="100px">
          <el-form-item label="分类">
            <el-input v-model="getProductsForm.category" placeholder="请输入分类"></el-input>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="getProductsForm.name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="供应商">
            <el-input v-model="getProductsForm.supplier" placeholder="请输入供应商"></el-input>
          </el-form-item>
          <el-form-item label="页码">
            <el-input-number v-model="getProductsForm.page" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="每页数量">
            <el-input-number v-model="getProductsForm.limit" :min="1" :max="50"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleGetProducts">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getProductsResult }}</pre>
        </div>
      </div>
      
      <!-- 获取商品详情 -->
      <div class="api-section">
        <h3>2.2 获取商品详情</h3>
        <el-form :model="getProductDetailForm" label-width="100px">
          <el-form-item label="商品ID">
            <el-input v-model="getProductDetailForm.id" placeholder="请输入商品ID"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleGetProductDetail">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getProductDetailResult }}</pre>
        </div>
      </div>
      
      <!-- 创建商品 -->
      <div class="api-section">
        <h3>2.3 创建商品 (管理员/采购员)</h3>
        <el-form :model="createProductForm" label-width="120px">
          <el-form-item label="商品名称">
            <el-input v-model="createProductForm.name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="分类">
            <el-input v-model="createProductForm.category" placeholder="请输入分类"></el-input>
          </el-form-item>
          <el-form-item label="单位">
            <el-input v-model="createProductForm.unit" placeholder="请输入单位"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input-number v-model="createProductForm.price" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
          <el-form-item label="成本价">
            <el-input-number v-model="createProductForm.cost_price" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
          <el-form-item label="最低库存">
            <el-input-number v-model="createProductForm.min_stock" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="供应商">
            <el-input v-model="createProductForm.supplier" placeholder="请输入供应商"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="createProductForm.description" type="textarea" placeholder="请输入描述"></el-input>
          </el-form-item>
          <el-form-item label="图片URL">
            <el-input v-model="createProductForm.image_url" placeholder="请输入图片URL"></el-input>
          </el-form-item>
          <el-form-item label="过期预警天数">
            <el-input-number v-model="createProductForm.expiry_warning" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleCreateProduct">创建</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ createProductResult }}</pre>
        </div>
      </div>
      
      <!-- 更新商品 -->
      <div class="api-section">
        <h3>2.4 更新商品 (管理员/采购员)</h3>
        <el-form :model="updateProductForm" label-width="120px">
          <el-form-item label="商品ID">
            <el-input v-model="updateProductForm.id" placeholder="请输入商品ID"></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="updateProductForm.name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="分类">
            <el-input v-model="updateProductForm.category" placeholder="请输入分类"></el-input>
          </el-form-item>
          <el-form-item label="单位">
            <el-input v-model="updateProductForm.unit" placeholder="请输入单位"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input-number v-model="updateProductForm.price" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
          <el-form-item label="成本价">
            <el-input-number v-model="updateProductForm.cost_price" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
          <el-form-item label="最低库存">
            <el-input-number v-model="updateProductForm.min_stock" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="供应商">
            <el-input v-model="updateProductForm.supplier" placeholder="请输入供应商"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="updateProductForm.description" type="textarea" placeholder="请输入描述"></el-input>
          </el-form-item>
          <el-form-item label="图片URL">
            <el-input v-model="updateProductForm.image_url" placeholder="请输入图片URL"></el-input>
          </el-form-item>
          <el-form-item label="过期预警天数">
            <el-input-number v-model="updateProductForm.expiry_warning" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="updateProductForm.status" placeholder="请选择状态">
              <el-option label="激活" value="active"></el-option>
              <el-option label="禁用" value="inactive"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpdateProduct">更新</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ updateProductResult }}</pre>
        </div>
      </div>
      
      <!-- 获取低库存商品 -->
      <div class="api-section">
        <h3>2.5 获取低库存商品</h3>
        <el-button type="primary" @click="handleGetLowStockProducts">获取低库存商品</el-button>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getLowStockProductsResult }}</pre>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'; // Ensure getToken is imported if not already

// 用户登录
const loginForm = reactive({
  username: '',
  password: ''
});
const loginResult = ref('');

const handleLogin = async () => {
  try {
    const response = await axios.post('/api/users/login/', loginForm);
    loginResult.value = JSON.stringify(response.data, null, 2);
    if (response.data.access) {
      localStorage.setItem('token', response.data.access);
      ElMessage.success('登录成功');
    } else {
      ElMessage.error('登录失败: 未获取到token');
    }
  } catch (error) {
    loginResult.value = JSON.stringify(error.response?.data || error.message, null, 2);
    ElMessage.error('登录失败');
  }
};

// 获取商品列表
const getProductsForm = reactive({
  category: '',
  name: '',
  supplier: '',
  page: 1,
  limit: 10
})
const getProductsResult = ref('')

const handleGetProducts = async () => {
  try {
    const token = getToken() // 添加Token检查
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    const params = {}
    if (getProductsForm.category) params.category = getProductsForm.category
    if (getProductsForm.name) params.name = getProductsForm.name
    if (getProductsForm.supplier) params.supplier = getProductsForm.supplier
    if (getProductsForm.page) params.page = getProductsForm.page
    if (getProductsForm.limit) params.limit = getProductsForm.limit
    
    const response = await axios.get('/api/products', {
      params,
      headers: { // 添加headers
        'Authorization': `Bearer ${token}`
      }
    })
    getProductsResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('获取成功')
  } catch (error) {
    getProductsResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('获取失败')
  }
}

// 获取商品详情
const getProductDetailForm = reactive({
  id: ''
})
const getProductDetailResult = ref('')

const handleGetProductDetail = async () => {
  try {
    const token = getToken() // 添加Token检查
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    if (!getProductDetailForm.id) {
      ElMessage.warning('请输入商品ID')
      return
    }
    
    const response = await axios.get(`/api/products/${getProductDetailForm.id}`, {
      headers: { // 添加headers
        'Authorization': `Bearer ${token}`
      }
    })
    getProductDetailResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('获取成功')
  } catch (error) {
    getProductDetailResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('获取失败')
  }
}

// 创建商品
const createProductForm = reactive({
  name: '',
  category: '',
  unit: '',
  price: 0,
  cost_price: 0,
  min_stock: 0,
  supplier: '',
  description: '',
  image_url: '',
  expiry_warning: 3
})
const createProductResult = ref('')

const handleCreateProduct = async () => {
  try {
    const token = getToken() // 添加Token检查
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    const response = await axios.post('/api/products/', createProductForm, { // createProductForm.value 调整为 createProductForm
      headers: { 
        'Authorization': `Bearer ${token}`
      }
    }); 
    createProductResult.value = response.data;
    ElMessage.success('商品创建成功');
  } catch (error) {
    createProductResult.value = error.response ? error.response.data : error.message;
    ElMessage.error('商品创建失败');
  }
};

// 更新商品
const updateProductForm = reactive({
  id: '',
  name: '',
  category: '',
  unit: '',
  price: 0,
  cost_price: 0,
  min_stock: 0,
  supplier: '',
  description: '',
  image_url: '',
  expiry_warning: 3,
  status: 'active'
})
const updateProductResult = ref('')

const handleUpdateProduct = async () => {
  try {
    const token = getToken() 
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    if (!updateProductForm.id) { // updateProductForm.value.id 调整为 updateProductForm.id
      ElMessage.warning('请输入商品ID')
      return
    }
        
    const response = await axios.put(`/api/products/${updateProductForm.id}/`, updateProductForm, { // updateProductForm.value 调整为 updateProductForm
      headers: { 
        'Authorization': `Bearer ${token}`
      }
    }); 
    updateProductResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('更新成功')
  } catch (error) {
    updateProductResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('更新失败')
  }
}

// 新增：获取低库存商品
const getLowStockProductsResult = ref('')

const handleGetLowStockProducts = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.get('/api/inventory/low-stock/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    // 处理响应数据
    const data = response.data?.data || response.data?.results || response.data || []
    const formattedData = (Array.isArray(data) ? data : []).map(item => ({
      id: item.product?.id || item.id,
      name: item.product_name || (item.product && item.product.name) || '未知产品',
      current_stock: item.current_stock || 0,
      min_stock: item.min_stock || 0,
      warehouse: item.warehouse_name || (item.warehouse && item.warehouse.name) || '未知仓库',
      status: item.status || 'unknown'
    }))

    getLowStockProductsResult.value = JSON.stringify(formattedData, null, 2)
    ElMessage.success('获取低库存商品成功')
  } catch (error) {
    getLowStockProductsResult.value = JSON.stringify(error.response?.data || error.message, null, 2)
    ElMessage.error('获取低库存商品失败')
  }
}
</script>

<style scoped>
.api-test-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.api-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.api-section:last-child {
  border-bottom: none;
}

.api-result {
  margin-top: 15px;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}
</style>